<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div>1.按钮模拟节流：<input type="button" id="throttle" value="提交"></div>
  <div>2.输入框模拟防抖：<input type="text" id="debounce"></div>

  <script>
    // 模拟 ajax 请求
    function sendAjax(content) {
      console.log(content);
    }

    // 节流函数
    function throttle(fn, interval) {
      let last = 0;
      return function(...args) {
        let now = +new Date();
        if (now - last < interval) return ;
        fn.apply(this, args);
        last = now;
      };
    }
    let count = 0;
    let throttleAjax = throttle(sendAjax, 3000);
    // 给按钮添加点击事件
    let btn = document.getElementById('throttle');
    btn.addEventListener('click', () => {
      // 注意：短时间内一直点击按钮，事件会一直触发，但是 sendAjax 只会三秒触发一次
      throttleAjax(`第${++count}次点击提交按钮`);
    });

    // 防抖函数
    function debounce(fn, delay) {
      let timer = null;
      return function(...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, args);
        }, delay);
      };
    }

    let debounceAjax = debounce(sendAjax, 3000);
    let input = document.getElementById('debounce');
    // 给输入框增加键盘 keyup 事件
    input.addEventListener('keyup', (e) => {
      debounceAjax(e.target.value);
    })
  </script>
</body>
</html>